<!-- 设备巡检-巡检计划-查看页面-->
<template>
  <div v-if="!isMain && isDetail" class="view-plan-detail" :class="{ isFromTask: isFromTask }">
    <div class="view-plan-detail-content">
      <!-- 顶部按钮 -->
      <div v-if="!isFromTask" class="view-plan-detail-top mb-[16px]">
        <px-button type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
        <!-- <div style="margin-left: 8px">{{ detailData.planName }}</div>
        <div style="margin-left: 8px">{{ detailData.planCode }}</div> -->
        <div class="text">{{ detailData.planName }} {{ detailData.planCode }}</div>
        <div>
          <px-tag class="ml-[16px]" :type="tagArr[detailData['planStatus']]">{{ detailData["planStatusDesc"] }}</px-tag>
        </div>
        <px-button
          v-if="detailData['planStatus'] == 1 || detailData['planStatus'] == 2"
          type="primary"
          class="view-plan-detail-top-edit"
          @click="editPlan"
          >编辑计划</px-button
        >
        <px-button v-if="detailData['planStatus'] == 3" type="primary" class="view-plan-detail-top-edit" @click="editPlan">修改计划</px-button>
      </div>
      <CustomTabs
        v-if="(detailData.planStatus == 3 || detailData.planStatus == 4) && !isFromTask"
        :tabList="tabList"
        :activeName="activeName"
        style="margin-top: -16px; margin-bottom: 12px"
        @tabSelect="handelTabSelected"
      />
      <px-scrollbar
        v-if="activeName === 'first' || isFromTask"
        :max-height="(detailData.planStatus == 3 || detailData.planStatus == 4) && !isFromTask ? 'calc(100vh - 290px)' : 'calc(100vh - 220px)'"
        class="plan-body"
      >
        <div ref="basicsRef" class="view-plan-title">基本信息</div>
        <div class="view-plan-wrap">
          <div class="view-plan-content">
            <div class="view-plan-item">
              <div class="label">科室</div>
              <div class="text">{{ detailData.classNameDesc }}</div>
            </div>
            <div class="view-plan-item">
              <div class="label">巡检类型</div>
              <div class="text">{{ detailData.inspectTypeDesc }}</div>
            </div>
            <div class="view-plan-item">
              <div class="label">任务分配</div>
              <div class="text">{{ detailData.groupName }}</div>
            </div>
          </div>
          <div class="view-plan-content">
            <div class="view-plan-item item-row">
              <div class="label">说明</div>
              <div class="text">{{ detailData.description || "-" }}</div>
            </div>
          </div>
        </div>
        <div ref="periodRef" class="view-plan-title">执行周期</div>
        <div class="view-plan-wrap">
          <div class="view-plan-content">
            <div class="view-plan-item">
              <div class="label">执行方式</div>
              <div class="text">{{ ["", "固定时间", "周期时间"][detailData.execType] }}</div>
            </div>
            <div class="view-plan-item">
              <div class="label">开始时间</div>
              <div class="text">{{ detailData.execStartDate }}</div>
            </div>
            <div class="view-plan-item">
              <div class="label">结束时间</div>
              <div class="text">{{ detailData.execEndDate }}</div>
            </div>
          </div>
          <template v-if="detailData.execType == 2">
            <div class="view-plan-content">
              <div class="view-plan-item plus">
                <div class="label">排查周期</div>
                <div v-if="detailData.cyclePerUnit !== 'YEAR'" class="text">
                  {{ dealExecTime() }}
                  <px-tag v-for="item in weeks" :key="item" class="ml-[6px]" type="info">{{ item }}</px-tag>
                  <px-tag v-for="item in days" :key="item" class="ml-[6px]" type="info">{{ item }}</px-tag>
                </div>
                <div v-else class="text">
                  {{ dealExecTime() }}
                  <px-tag v-for="item in months" :key="item" class="ml-[3px] mr-[3px]" type="info">{{ item }}</px-tag>
                  的
                  <px-tag v-for="item in days" :key="item" class="ml-[3px] mr-[3px]" type="info">{{ item }}</px-tag>
                  日
                </div>
              </div>
            </div>
            <div class="view-plan-content">
              <div class="view-plan-item">
                <div class="label">任务执行时间</div>
                <div class="text">
                  <px-tag v-for="item in operates" :key="item" class="ml-[3px] mr-[3px]" type="info">{{ item }}</px-tag>
                </div>
              </div>
              <div class="view-plan-item">
                <div class="label">执行时长</div>
                <div class="text">{{ `${detailData.execDuration}${unitList[detailData.execDurationUnit]}` }}</div>
              </div>
              <div class="view-plan-item">
                <div class="label">宽泛期</div>
                <div class="text">{{ `${detailData.extendDuration}${unitList[detailData.extendDurationUnit]}` }}</div>
              </div>
            </div>
            <div class="view-plan-content">
              <div class="view-plan-item plus">
                <div class="label">任务生成并提醒时间</div>
                <div class="text">{{ taskList[detailData.taskCreateTime] }}</div>
              </div>
            </div>
          </template>
        </div>
        <!-- 巡检规则 -->
        <div ref="equipRef" class="view-plan-title">巡检规则</div>
        <div class="view-plan-wrap noborder">
          <div class="view-plan-content">
            <InspectRulesTable :table-data="tableEqiupSelected" :tableColumns="tableEqiupColums" :total="0" class="w-[100%]" />
          </div>
        </div>
      </px-scrollbar>
      <!-- 巡检任务页面 -->
      <div v-if="activeName === 'second'">
        <px-table row-key="id" :data="taskTable" class="inspect-table" size="small" height="calc(100vh - 311px)" border>
          <px-table-column type="index" align="center" min-width="60" fixed="left" />
          <template v-for="(item, index) in taskTableColumns" :key="index">
            <px-table-column
              :label="item.label"
              :min-width="item.minWidth"
              :align="item.align"
              :show-overflow-tooltip="item.showOverflowTooltip"
              :fixed="item.fixed"
            >
              <template v-if="item.prop === 'taskType'" #default="scope">
                <div v-if="scope.row.taskStatusDesc" class="status">
                  <div class="circle" :style="{ backgroundColor: `${TAG_CONFIG[scope.row.taskStatus]?.color}` }" />
                  <p :style="{ color: `${TAG_CONFIG[scope.row.taskStatus]?.color}` }">{{ scope.row.taskStatusDesc }}</p>
                </div>
                <span v-else>-</span>
              </template>

              <template v-else #default="scope">{{
                scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
              }}</template>
            </px-table-column>
          </template>

          <px-table-column fixed="right" label="操作" min-width="180" align="center">
            <template #default="scope">
              <px-tooltip content="详情" placement="top">
                <px-button link type="primary" icon="Tickets" @click="handleView(scope.row)" />
              </px-tooltip>
            </template>
          </px-table-column>
        </px-table>
        <pagination
          v-show="total > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          class="inspection-pagination"
          :total="total"
          @pagination="queryTable"
        />
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { inspectPlanView, inspectPlanViewByCode } from "@/api/equip/inspect";
import { queryInspectTask } from "@/api/equip/inspectTask";
import CustomTabs from "@/components/Tabs/index.vue";
import { cloneDeep } from "@pureadmin/utils";
import { ref, watch } from "vue";
import { useRouter } from "vue-router";
import { TAG_CONFIG } from "../../task/config";
import { TableItem } from "../../types";
import InspectRulesTable from "./InspectRulesTable.vue";

const router = useRouter();
const isFromTask = defineModel("isFromTask");
const isMain = defineModel("isMain");
const isDetail = defineModel("isDetail");
const planNo = defineModel("planNo");
// const planCode = defineModel("planCode");
const isAdd = defineModel("isAdd");
const isUpdate = defineModel("isUpdate");

const tabList = ref([
  {
    name: "first",
    label: "巡检计划"
  },
  {
    name: "second",
    label: "巡检任务"
  }
]);
const activeName = ref("first");
// 巡检规则table
const tableData = ref([]);
//选择设备table
const tableEqiupSelected = ref([]);
//巡检任务table
const taskTable = ref([]);
const total = ref(0);
const queryParams = ref({
  pageNum: 1,
  pageSize: 20,
  planCode: ""
});

const detailDataTmpl = {
  planCode: "", //计划编号
  planName: "", //计划名称
  className: "",
  groupCode: "",
  planStatus: 0,
  execType: "1", //执行方式 1-固定时间,2-周期时间
  inspectType: 1, //巡检类型
  execStartDate: "", //执行开始日期
  execEndDate: "", //执行结束日期
  execDuration: 0, //执行时长
  execDurationUnit: "HOUR", //执行时长单位
  extendDuration: 0, //宽泛期
  extendDurationUnit: "HOUR", //宽泛期单位
  cyclePerNum: 0, //排查周期
  cyclePerUnit: "DAY", //	排查周期单位
  cycleValue: "", //排查周期值
  cycleTime: "", //周期时间
  taskCreateTime: "", //	任务生成并提醒时间
  description: "",
  ruleCodeList: [] //回显数据保存-规则编码列表
};
const detailData = ref(cloneDeep(detailDataTmpl));
const weeksMap = {
  MONDAY: "星期一",
  TUESDAY: "星期二",
  WEDNESDAY: "星期三",
  THURSDAY: "星期四",
  FRIDAY: "星期五",
  SATURDAY: "星期六",
  SUNDAY: "星期日"
};
const monthArr = Array.from({ length: 12 }, (_, i) => `${i + 1}月`);
const operateTimeArr = Array.from({ length: 24 }, (_, i) => (i < 10 ? `0${i}:00` : `${i}:00`));
const unitList = {
  DAY: "日",
  HOUR: "小时"
};
const taskList = ["", "准点生成", "提前10分钟", "提前30分钟", "提前1小时", "提前1天"];
const weeks = ref([]);
const days = ref([]);
const months = ref([]);
const operates = ref([]);

const tagArr = ["", "info", "warning", "", "danger"];

const tableEqiupColums = ref<TableItem[]>([
  // all-巡检计划 -设备规则表格
  { prop: "index", minWidth: "55", fixed: "left" },
  { prop: "ruleCode", label: "巡检规则编号", minWidth: "160", showOverflowTooltip: true, fixed: "left" },
  { prop: "ruleName", label: "巡检规则名称", minWidth: "160", showOverflowTooltip: true, fixed: "left" },
  { prop: "inspectTypeDesc", label: "巡检类型", minWidth: "160", showOverflowTooltip: true },
  { prop: "classNameDesc", label: "科室", minWidth: "60", showOverflowTooltip: true },
  { prop: "inspectAreaDesc", label: "巡检区域", minWidth: "160", showOverflowTooltip: true }
]);
// 巡检任务表格
const taskTableColumns = ref<TableItem[]>([
  { prop: "taskCode", label: "任务(工单)编号", minWidth: "160", showOverflowTooltip: true, fixed: "left" },
  { prop: "planCode", label: "所属计划编号", minWidth: "160", showOverflowTooltip: true },
  { prop: "taskName", label: "任务名称", minWidth: "240", showOverflowTooltip: true },
  { prop: "startTime", label: "任务开始时间", minWidth: "140", showOverflowTooltip: true },
  { prop: "classNameDesc", label: "科室", minWidth: "60", showOverflowTooltip: true },
  { prop: "taskStatusDesc", label: "状态", minWidth: "120", type: "status", showOverflowTooltip: true },
  { prop: "groupCodeName", label: "执行组", minWidth: "120", showOverflowTooltip: true },
  { prop: "executorName", label: "执行人", minWidth: "80", showOverflowTooltip: true }
]);
watch(
  () => isDetail.value,
  async () => {
    if (isDetail.value) {
      if (!planNo.value) {
        backMainPage();
        return;
      } else {
        let detail: any = {};
        if (isFromTask.value) {
          detail = await inspectPlanViewByCode({ planCode: planNo.value });
        } else {
          detail = await inspectPlanView({ id: planNo.value });
        }
        detail.execType = String(detail?.execType);
        const { checkRuleList, ruleDTOList, cycleTime, planCode } = detail as any;
        queryParams.value.planCode = planCode;
        queryTable();
        tableData.value = checkRuleList?.length > 0 ? checkRuleList : [];
        tableEqiupSelected.value = ruleDTOList?.length > 0 ? ruleDTOList : []; //设备规则表格回显
        detailData.value = detail;
        if (cycleTime) {
          const arr = cycleTime.split(",").sort((a, b) => a - b);
          operates.value = arr.reduce((pre, cur) => {
            return [...pre, operateTimeArr[cur]];
          }, []);
        }
      }
    } else {
      planNo.value = "";
    }
  }
);
function reset() {
  detailData.value = cloneDeep(detailDataTmpl);
  weeks.value = [];
  days.value = [];
  months.value = [];
  operates.value = [];
  activeName.value = "first";
}
function backMainPage() {
  isDetail.value = false;
  isMain.value = true;
  planNo.value = "";
  reset();
}
function handelTabSelected(selectName) {
  activeName.value = selectName;
}
function editPlan() {
  const row = detailData.value;
  const { id: planNumber, planStatus } = row;
  planNo.value = planNumber;
  isDetail.value = false;
  if ([1, 2].indexOf(planStatus) !== -1) {
    isAdd.value = true;
  } else {
    isMain.value = true;
    isUpdate.value = true;
  }
}
function resetTime() {
  weeks.value = [];
  days.value = [];
  months.value = [];
}
function dealExecTime() {
  resetTime();
  if (detailData.value.cyclePerUnit === "YEAR") {
    if (detailData.value.cycleValue) {
      const [month, day] = (detailData.value.cycleValue as string).split("-");
      if (day) {
        let arr: any[] = day.split(",");

        days.value = arr.sort((a, b) => a - b);
      }
      if (month) {
        let arr: any[] = month.split(",").sort((a: any, b: any) => a - b);

        months.value = arr.reduce((cur, pre) => {
          return [...cur, monthArr[Number(pre) - 1]];
        }, []);
      }
      return `每${detailData.value.cyclePerNum}年的`;
    }
  } else if (detailData.value.cyclePerUnit === "DAY") {
    if (detailData.value.cyclePerNum) {
      return `每${detailData.value.cyclePerNum}天`;
    }
  } else if (detailData.value.cyclePerUnit === "WEEK") {
    if (detailData.value.cyclePerNum) {
      if (detailData.value.cycleValue) {
        let arr = detailData.value.cycleValue.split(",");
        arr.forEach(item => {
          weeks.value.push(weeksMap[item]);
        });
      }
      return `每${detailData.value.cyclePerNum}周的`;
    }
  } else if (detailData.value.cyclePerUnit === "MONTH") {
    if (detailData.value.cyclePerNum) {
      if (detailData.value.cycleValue) {
        let arr = detailData.value.cycleValue.split(",");

        days.value = arr.sort((a, b) => a - b);
      }
      return `每${detailData.value.cyclePerNum}月的`;
    }
  }
}

const queryTable = async () => {
  const params = JSON.parse(JSON.stringify(queryParams.value));
  const data = await queryInspectTask(params);
  taskTable.value = data?.data;
  total.value = data?.total;
};
const handleView = (row: any) => {
  let path = `/all/equip/inspect/task`;
  router.push({
    path: path,
    query: { reffer: "plan", taskCode: row.id }
  });
};
</script>
<style lang="scss" scoped>
@import url("../../scss/view-detail.scss");

.isFromTask {
  height: 100% !important;
  padding: 0;
}

.text {
  margin-left: 20px;
  font-size: 20px;
  color: rgb(0 0 0 / 90%);
  font-weight: bold;
}
.view-plan-detail .view-plan-wrap .view-plan-content {
  .view-plan-item.item-row {
    width: 100%;
  }
}
</style>
